package engine;

import java.util.List;

import com.threed.jpct.Logger;

public class AIPlayer extends Thread {
	private static final int MIN_SEND_POINTS = 1;

	private Universe universe;
	private DifficultyLevel difficultyLevel;
	private boolean running;
	private int moveCounter;

	public AIPlayer(Universe universe, DifficultyLevel dl) {
		this.universe = universe;
		this.difficultyLevel = dl;
		running = true;
		moveCounter = 0;
	}

	public void run() {
		try {
			Thread.sleep(difficultyLevel.getStartDelay());
		} catch (InterruptedException e) {
			Logger.log(e.getMessage());
		}

		while (running) {
			for (Planet p : universe.getPlanets()) {
				if (p.getOwner() == Ownership.ENEMY) {
					if (moveCounter == difficultyLevel.getDefensiveMovementRatio()) {
						defensiveMove(p);
						moveCounter = 0;
					} else {
						offensiveMove(p);
					}
					moveCounter++;

					try {
						Thread.sleep(difficultyLevel.getDecisionInterval());
					} catch (InterruptedException e) {
						Logger.log(e.getMessage());
					}
				}
			}
		}
	}

	private void offensiveMove(Planet planet) {
		if (planet.getPoints() * difficultyLevel.getOffensiveAggressivness() > MIN_SEND_POINTS) {
			Ship ship = new Ship(universe.getWorld(), planet, getWeakestPlanet(universe.getPlanets()), (int) (planet.getPoints() * difficultyLevel.getOffensiveAggressivness()));
			ship.setOwner(Ownership.ENEMY);
			universe.addShip(ship);
		}
	}

	private void defensiveMove(Planet planet) {
		if (planet.getPoints() * difficultyLevel.getDefensiveAggressivness() > MIN_SEND_POINTS) {
			Ship ship = new Ship(universe.getWorld(), planet, getOwnWeakestPlanet(universe.getPlanets()), (int) (planet.getPoints() * difficultyLevel.getDefensiveAggressivness()));
			ship.setOwner(Ownership.ENEMY);
			universe.addShip(ship);
		}
	}

	public void destroyPlayer() {
		running = false;
	}

	private Planet getWeakestPlanet(List<Planet> planets) {
		Planet weakestPlanet = planets.get(0);
		for (int i = 0; i < planets.size(); i++) {
			if (planets.get(i).getOwner() != Ownership.ENEMY)
				if (planets.get(i).getPoints() < weakestPlanet.getPoints())
					weakestPlanet = planets.get(i);
		}
		return weakestPlanet;
	}

	private Planet getOwnWeakestPlanet(List<Planet> planets) {
		Planet weakestPlanet = planets.get(0);
		for (int i = 0; i < planets.size(); i++) {
			if (planets.get(i).getOwner() == Ownership.ENEMY)
				if (planets.get(i).getPoints() < weakestPlanet.getPoints())
					weakestPlanet = planets.get(i);
		}
		return weakestPlanet;
	}
}
